import {creepNumConfig} from "./creepNumConfig.js";


/**
 * creep生成方法
 * @param {StructureSpawn} spawn
 * @param {string} role
 * @param {string} roomKey
 */
export const creatCreep = (spawn, roomKey, role) => {
    const date = new Date()
    const name = `xl-${roomKey}-${date.getHours()}-${date.getMinutes()}-${date.getSeconds()}`
    //判断是否有足够的能量
    if (useEnergy(roomKey, role) <= Game.rooms[roomKey].energyAvailable) {
        const result_code = spawn.spawnCreep(creepNumConfig[roomKey][role].bodys, `${name}-${role}`, {
            memory: {
                role: role,
                workState: false,
                spawnId: spawn.id
            }
        })
        console.log(`创建了${name}-${role}::${result_code}`)
    }
}

/**
 * @param  {string} role 角色
 * @param {string} roomKey 房间号
 * @returns {number|null|((value: number) => CSSUnitValue)|string|*}
 */
export const creepNum = (role, roomKey) => {
    return creepNumConfig[roomKey][role].number
}

/**
 * @description 组装成新的role列表并通过权重字段来排序
 * @param {string} roomKey 房间号
 * @param {Array[string]} excludeRoles 要排除的角色，部分角色不走正常的生成模块，比如防御者只在战争模块生成
 * @return {Array[string]} 角色数组
 */
export const getSortedRolesByWeight = (roomKey, ...excludeRoles) => {
    // 获取指定房间的配置
    const roomConfig = creepNumConfig[roomKey];
    // 创建角色信息列表
    const roles = Object.keys(roomConfig)
        .map((key) => {
            return {
                role: roomConfig[key].role,
                weight: roomConfig[key].weight,
            };
        })
        .filter((item) => !excludeRoles.includes(item.role));

    // 按权重从低到高排序
    roles.sort((a, b) => a.weight - b.weight);

    // 返回排序后的角色列表（只包含 role 字段）
    return roles.map((item) => item.role);
};

/**
 * 角色执行逻辑
 * @param roomKey
 * @param creep
 * @param role
 */
export const roleRun = (roomKey, creep, role) => {
    if (creepNumConfig[roomKey][role]) {
        creepNumConfig[roomKey][role].func(creep, creepNumConfig[roomKey][role].sourcesIndex)
    }
}

/**
 * 计算生成一个creep需要多少能量
 * @param roomKey
 * @param role
 * @return {number}
 */
const useEnergy = (roomKey, role) => {
    let sum = 0
    for (const body of creepNumConfig[roomKey][role].bodys) {
        if (body === MOVE || body === CARRY) {
            sum += 50
        }
        if (body === WORK) {
            sum += 100
        }
        if (body === ATTACK) {
            sum += 80
        }
        if (body === RANGED_ATTACK) {
            sum += 150
        }
        if (body === HEAL) {
            sum += 250
        }
        if (body === CLAIM) {
            sum += 600
        }
        if (body === TOUGH) {
            sum += 10
        }
    }
    return sum
}